package com.lbiuse.cwc.session;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NoAuthXML {
	
	private static final Logger logger = Logger.getLogger(NoAuthXML.class);
	private List<RegPattern> listRegPattern = new ArrayList<RegPattern>();

	public NoAuthXML() {
	}

	@SuppressWarnings("unchecked")
	private void readXmlToMap(String xmlFile) throws Exception {
		if (StringUtils.isEmpty(xmlFile)) {
			return;
		}
		
		// 获得文档对象
		SAXReader saxReader = new SAXReader();
		String fileName = NoAuthXML.class.getClassLoader()
			.getResource(xmlFile).getPath();
		Document doc = saxReader.read(new File(fileName));
		Element root = doc.getRootElement();
		List<Element> children = root.elements();
		for (Element child : children) {
			String reg = child.elementText("url-pattern");
			RegPattern regPattern = new RegPattern(reg);
			listRegPattern.add(regPattern);
		}
	}

	public static void main(String[] args) throws Exception {
		NoAuthXML noAuth = new NoAuthXML();
		noAuth.init("noAuth.xml");
		boolean b = false;
		b = noAuth.matcher("www.baidu.com");
		b = noAuth.matcher("/bs/partsbd/edit/");
		b = noAuth.matcher("/bs/partsbd/insert/");
		b = noAuth.matcher("bs/parts/edit/");
		System.out.println(b);
	}

	public void init(String xmlFile) {
		try {
			logger.debug("init xmlFile:" + xmlFile);
			readXmlToMap(xmlFile);
		} catch (Exception e) {
			logger.error("init", e);
		}
	}

	public boolean matcher(String url) {
		boolean bReturn = false;
		for (int i=0; i<listRegPattern.size(); i++) {
			bReturn = listRegPattern.get(i).matcher(url);
			if (bReturn) {
				break;
			}
		}
		return bReturn;
	}
	
	class RegPattern {
		String reg;
		Pattern pattern;
		Matcher m;
		
		public RegPattern(String reg) {
			this.reg = reg;
			pattern = Pattern.compile(reg); 
		}
		
		public boolean matcher(String url) {
			m = pattern.matcher(url);
			return m.find();
		}
		
		
	}
}
